package com.fulihui.wgj.dal.mybatis.repository;

import com.fulihui.common.enums.TemplateStatusEnum;
import com.fulihui.weixinsdk.model.Template;
import com.fulihui.wgj.dal.mybatis.domain.WxTemplate;
import com.fulihui.wgj.dal.mybatis.mapper.WxTemplateMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author wang_wx
 * @date 2018-06-20
 */
@Component
public class WxTemplateRepository extends BaseRepository<WxTemplate> {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxTemplateRepository.class);

    @Resource
    WxTemplateMapper wxTemplateMapper;

    public List<String> queryDeputyIndustry(String appId) {
        return wxTemplateMapper.queryDeputyIndustry(appId);
    }

    /**
     * 根据appId更新模板状态
     *
     * @param appId
     * @param status {@link com.fulihui.common.enums.TemplateStatusEnum}
     * @return
     */
    public int updateStatusByAppId(String appId, Long status) {
        Example example = new Example(WxTemplate.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(appId)) {
            criteria.andEqualTo("appId", appId);
            WxTemplate wxTemplate = new WxTemplate();
            wxTemplate.setStatus(status);
            wxTemplate.setGmtModified(new Date());
            return wxTemplateMapper.updateByExampleSelective(wxTemplate, example);
        }
        return 0;
    }

    /**
     * 同步模板消息
     *
     * @param appId        公众号appId
     * @param templateList 模板列表
     */
    @Transactional(value = "mysqlTransactionManager", rollbackFor = Exception.class)
    public void syncTemplate(String appId, List<Template> templateList) {
        // 1. 更新本地所有模板为无效
        updateStatusByAppId(appId, TemplateStatusEnum.invalid.getValue());
        // 2. 新模版添加或者更新到本地
        if (!CollectionUtils.isEmpty(templateList)) {
            templateList.forEach(template -> {
                String templateId = template.getTemplate_id();
                String templateTitle = template.getTitle();
                String templatePrimaryIndustry = template.getPrimary_industry();
                String templateDeputyIndustry = template.getDeputy_industry();
                String templateContent = template.getContent();
                String templateExample = template.getExample();
                WxTemplate wxTemplateQuery = new WxTemplate();
                wxTemplateQuery.setAppId(appId);
                wxTemplateQuery.setTemplateId(templateId);
                WxTemplate wxTemplateResult = this.queryOne(wxTemplateQuery);
                if (Objects.isNull(wxTemplateResult)) {
                    WxTemplate wxTemplate = new WxTemplate();
                    wxTemplate.setAppId(appId);
                    wxTemplate.setTemplateId(templateId);
                    wxTemplate.setContent(templateContent);
                    wxTemplate.setExample(templateExample);
                    wxTemplate.setPrimaryIndustry(templatePrimaryIndustry);
                    wxTemplate.setDeputyIndustry(templateDeputyIndustry);
                    wxTemplate.setTitle(templateTitle);
                    wxTemplate.setGmtCreate(new Date());
                    wxTemplate.setGmtModified(new Date());
                    // 微信会多返回一条默认无效的模板信息
                    if (StringUtils.isBlank(templatePrimaryIndustry) && StringUtils.isBlank(templateDeputyIndustry) && StringUtils.isBlank(templateExample)) {
                        wxTemplate.setStatus(TemplateStatusEnum.invalid.getValue());
                    } else {
                        wxTemplate.setStatus(TemplateStatusEnum.valid.getValue());
                    }
                    this.saveSelective(wxTemplate);
                } else {
                    wxTemplateResult.setContent(templateContent);
                    wxTemplateResult.setExample(templateExample);
                    wxTemplateResult.setPrimaryIndustry(templatePrimaryIndustry);
                    wxTemplateResult.setDeputyIndustry(templateDeputyIndustry);
                    wxTemplateResult.setTitle(templateTitle);
                    wxTemplateResult.setGmtModified(new Date());
                    // 微信会多返回一条默认无效的模板信息
                    if (StringUtils.isBlank(templatePrimaryIndustry) && StringUtils.isBlank(templateDeputyIndustry) && StringUtils.isBlank(templateExample)) {
                        wxTemplateResult.setStatus(TemplateStatusEnum.invalid.getValue());
                    } else {
                        wxTemplateResult.setStatus(TemplateStatusEnum.valid.getValue());
                    }
                    this.updateSelective(wxTemplateResult);
                }
            });
        }
    }

}
